package com.thuan.hibernate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import pojo.ChessOnlineRoom;
import pojo.League;
import pojo.Reward;
import pojo.UserAccount;
import server.Server;
import transfer.LeagueData;
import transfer.LeagueRoomData;
import transfer.UserAccountData;


public class LeagueTimer {

  Timer timer;
  League league;
  Server server;
  
  public LeagueTimer(Server server, League league, int delay, int period) {
    timer = new Timer();
    this.server = server;
    this.league = league;
    timer.scheduleAtFixedRate(new RemindTask(), delay * 1000, period * 1000);
  }
	
  class RemindTask extends TimerTask {
    public void run() {
		if(league.getEndDate().compareTo(new Date()) < 0){
			if(!isExistLeagueRoomPlaying()){
				updateRewardForWinners();
				System.out.println("Stop Timer LeagueId: " + league.getLeagueId() + " - " + new Date());
				timer.cancel();
			}
		} else System.out.println("Running Timer LeagueId: " + league.getLeagueId() + " - " + new Date());	
    }
  }

  public void updateRewardForWinners(){
		Reward reward = Repository.findReward(league.getReward().getRewardId());
		List<Integer> listLeagueScore = Repository.topLeagueScore(league.getLeagueId());
		int prize;
		
		for(int i = 0; i < listLeagueScore.size(); i++){
			if(i==0) prize = reward.getFirstPrize();
			else if(i==1) prize = reward.getSecondPrize();
			else prize = reward.getThirdPrize();
			List<UserAccount> listAcc = Repository.listPlayersOfScore(league.getLeagueId(), listLeagueScore.get(i));
			for(int j = 0; j < listAcc.size(); j++)
				Repository.updateRewardForWinner(listAcc.get(j).getUsername(), prize);
		}
	}
  
  public boolean isExistLeagueRoomPlaying(){
	  boolean result = false;
	  for(ChessOnlineRoom i : server.getRooms())
		  if(i != null && i.isLeague() && i.getLeagueId()==league.getLeagueId())
			  if(i.getPlayerB() != null)
				  result = true;
			  else{
				  server.removeRoom(i.getRoomId());
				  server.sendObject(new LeagueRoomData("List League Rooms", i.getLeagueId(), server.getRooms()));
				  server.sendObjectToId(new UserAccountData("Account", i.getPlayerA()), i.getmWorkerIdA());
				  ArrayList<League> list = new ArrayList<League>(Repository.listLeagues());
				  server.sendObjectToId(new LeagueData("List Leagues", i.getPlayerA(), list), i.getmWorkerIdA());
			  }
	  return result;	  
  }
}